package com.ws.ssmzongjie3.interceptor;

import com.ws.ssmzongjie3.bean.Acl_User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
//1,定义类实现 HandlerInterceptor  重写3个方法。重点是preHandle 返回true放行，false不放行（要给响应）
//2,SpringMvcConfig类中注册拦截器 配置拦截路径和排除路径   registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/dept/login");
//3,控制器中存在的路径才能经过拦截器 404的路径也不会经过拦截器

//3种情况， 1，不拦截   2，拦截后放行    3，拦截后重定向

//拦截器 springmvc  http://ip:8080/ssmjson/dept/add
//过滤器 /*  http://ip:8080/ssmjson/a.jsp   http://ip:8080/ssmjson/js/a.js
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI().substring(request.getContextPath().length());
        System.out.println("requestURI:"+requestURI);
        //获取用户登录时候放入到session中的user信息
        Acl_User user = (Acl_User) request.getSession().getAttribute("houuser");

//        if (user == null ){
//            //没有登录
//            //跳转到login.jsp且跳出iframe
//            PrintWriter writer = response.getWriter();
//            writer.write("<script>window.parent.location.href='"+request.getContextPath()+"/houuser/houlogin'</script>");
//            writer.close();
//            return false;
//        }
        //获取用户登录时候放入到session中的能操作的真实权限信息
        List<String> permissions = (List<String>) request.getSession().getAttribute("permissions");
        System.out.println(permissions);
        if (permissions!=null){
           if (permissions.contains(requestURI)){
               //有权限
               return true;
           }else {
               //无权限
               //跳转不是重定向
               request.getRequestDispatcher("/WEB-INF/admin/welcome.jsp").forward(request, response);
               return false;

           }
        }else {
            //没有登录
            //跳转到login.jsp且跳出iframe
            PrintWriter writer = response.getWriter();
            writer.write("<script>window.parent.location.href='"+request.getContextPath()+"/houuser/houlogin'</script>");
            writer.close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("控制器方法后  渲染视图前 postHandle 拦截器。。。。。。。。。。。。");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("最后  afterCompletion。。。。。。。。。。。。");
    }
}
